package com.tsy.graduate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tsy.graduate.bean.*;
import com.tsy.graduate.dto.ExamDTO;
import com.tsy.graduate.dto.HomeworkDTO;
import com.tsy.graduate.dto.NotebookDTO;
import com.tsy.graduate.exception.BusinessException;
import com.tsy.graduate.httpdto.ObjectCollectionResponse;
import com.tsy.graduate.httpdto.ObjectDataResponse;
import com.tsy.graduate.service.*;
import com.tsy.graduate.utils.GsonUtils;
import com.tsy.graduate.constant.WxAppConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.nimbus.NimbusStyle;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/tsy")
@RestController
@Api("练习题目接口")
public class ExerciseController {
    @Autowired
    UserService userService;

    @Autowired
    QuestionService questionService;

    @Autowired
    CourseService courseService;

    @Autowired
    ExamService examService;

    @Autowired
    LessonService lessonService;

    @Autowired
    HomeworkService homeworkService;

    @Autowired
    NotebookService notebookService;

    @Autowired
    CourseRecordService courseRecordService;

    @Autowired
    NotebookRecordService notebookRecordService;


    /**
     * 根据用户id获取该用户的错题本
     *
     * @param userId
     * @return
     */
    @ApiOperation("根据用户id 获取错题本")
    //使用@GetMapping(value = “/”)来代替@RequestMapping(value=”/”,method= RequestMethod.GET)
    @GetMapping("/noteBook")
    public ObjectDataResponse<NotebookDTO> getNoteBook(@RequestParam(value = "userId") Long userId) {
        NotebookDTO notebookDTO = new NotebookDTO();
        QueryWrapper<NotebookRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(NotebookRecord::getStudentId, userId);
        List<NotebookRecord> list = notebookRecordService.list(queryWrapper);
        list.forEach(record -> {
                    record.setQuestion(questionService.getById(record.getQuestionId()));
                }
        );
        notebookDTO.setNotebookRecordList(list);
        return new ObjectDataResponse<>(notebookDTO);
    }

    /**
     * 根据学生id获取已经学过的课程  或者根据教师id获取开设的课程列表
     *
     * @param userId
     * @return
     */
    @GetMapping("/courseByUserId")
    @ApiOperation("根据用户id 获取课程列表")
    public ObjectCollectionResponse<Course> getCourseByStudentId(@RequestParam(value = "userId") Long userId,
                                                                 @RequestParam(value = "type", required = false) Byte type) {

        //todo 通过记录表找到 学生的已学课程ids 然后查询course表获取course list
        QueryWrapper<CourseRecord> queryWrapper = new QueryWrapper<>();
        if (type == null || type == 3 || type == 0) {
            return new ObjectCollectionResponse<>(courseService.list(new QueryWrapper<>()));
        }
        if (type.equals(WxAppConstant.USER_TYPE_STUDENT)) {
            if (userId != null && userId > 0) {
                queryWrapper.lambda().eq(CourseRecord::getStudentId, userId);
            }
        } else {
            return new ObjectCollectionResponse<>(courseService.list(new QueryWrapper<Course>().lambda().eq(Course::getTeacherId, userId)));
        }
        List<CourseRecord> list = courseRecordService.list(queryWrapper);
        List<Long> idList = list.stream().map(CourseRecord::getCourseId).distinct().collect(Collectors.toList());
        if (idList.size() == 0) {
            throw new BusinessException(20002, "该用户没有对应的课程 请先创建课程 如果是学生用户还需要进行选课");
        }
        List<Course> courseList = (List<Course>) courseService.listByIds(idList);
        return new ObjectCollectionResponse<>(courseList);
    }

    /**
     * 根据课程id获取 该课程下的所有测验
     *
     * @param courseId
     * @return
     */
    @GetMapping("/examByCourseId")
    @ApiOperation("根据课程id获取 该课程下的所有测验(exams)")
    public ObjectCollectionResponse<Exam> getExamListByCourseId(@RequestParam(value = "courseId") Long courseId) {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Exam::getCourseId, courseId);
        return new ObjectCollectionResponse<>(examService.list(queryWrapper));
    }

    /**
     * 根据课程id获取该课程下的所有课后作业
     * 先用course去找lesson   通过lesson找homework
     * @param courseId
     * @return
     */
    @GetMapping("/homeworkByCourseId")
    @ApiOperation("根据课程id获取该课程下的所有课后作业")
    public ObjectCollectionResponse<Homework> getHomeworkListByCourseId(@RequestParam(value = "courseId") Long courseId) {

        QueryWrapper<Lesson> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Lesson::getCourseId, courseId);
        List<Long> lessonIdList = lessonService.list(queryWrapper).stream().map(Lesson::getId).collect(Collectors.toList());
        //                    lessonlist.stream().map(Lesson::getId).collect(Collectors.toList());
        return new ObjectCollectionResponse<Homework>(homeworkService.list(new QueryWrapper<Homework>()
                .lambda().in(Homework::getLessonId, lessonIdList)
        ).stream().distinct().collect(Collectors.toList()));
    }

    /**
     * 根据课程id获取该课程下的所有课后作业
     *
     * @param
     * @return
     */
    @GetMapping("/homeworkByLessonId")
    @ApiOperation("根据课程id获取该课程下的所有课后作业")
    public ObjectCollectionResponse<Homework> getHomeworkByLesson(@RequestParam(value = "lessonId") Long lessonId) {
        QueryWrapper<Homework> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Homework::getLessonId, lessonId);
        return new ObjectCollectionResponse<Homework>(homeworkService.list(queryWrapper));
    }

    /**
     * 根据课程id获取该课程下的所有小节
     * courseid  ->  all-lessons
     *
     *
     * @param courseId
     * @return
     */
    @GetMapping("/lessonsByCourseId")
    @ApiOperation("根据课程id获取该课程下的所有小节(lessons)")
    public ObjectCollectionResponse<Lesson> getLessonListByCourseId(@RequestParam(value = "courseId") Long courseId) {
        QueryWrapper<Lesson> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Lesson::getCourseId, courseId);
        List<Lesson> list = lessonService.list(queryWrapper);
        return new ObjectCollectionResponse<Lesson>(list);

    }


    /**
     * 根据课后作业id 获取该课后作业详情
     *
     * @param homeworkId
     * @return
     */
    @RequestMapping(value = "/homeworkDetails", method = RequestMethod.GET)
    @ApiOperation("根据课后作业id 获取该课后作业详情")
    public ObjectDataResponse<HomeworkDTO> getHomeworkDetailById(@RequestBody Long homeworkId) {
        Homework homework = homeworkService.getById(homeworkId);
        //此时 questionids = "[1,2,3,4,5]" 这时候是string
        List<Long> idList = GsonUtils.decodeList(homework.getQuestionIds(), Long.class);
        // idList = { 1,2,3,4,5 } 这时候是array
        HomeworkDTO homeworkDTO = new HomeworkDTO();
        homeworkDTO.setQuestions((List<Question>) questionService.listByIds(idList));
        //listbyids =  list(new QueryWrapper<Lesson>().lambda().in(Lesson::getId,idlist))

        homeworkDTO.setHomework(homework);
        return new ObjectDataResponse<>(homeworkDTO);
    }

    /**
     * 根据课后作业id 获取该课后作业详情
     *
     * @param lessonId
     * @return
     */
    @GetMapping(value = "/getQuestionsByLessonid")
    @ApiOperation("根据lessonid 获取该课后作业中的题目详情")
    public ObjectDataResponse<HomeworkDTO> getQuestionsByLessonid(@RequestParam() Long lessonId) {

        //lessonid -> lesson -> homework
        Homework homework = homeworkService.getOne(new QueryWrapper<Homework>()
                .lambda().eq(Homework::getLessonId, lessonId)
        );
        List<Long> idList = GsonUtils.decodeList(homework.getQuestionIds(), Long.class);
        HomeworkDTO homeworkDTO = new HomeworkDTO();
        homeworkDTO.setQuestions((List<Question>) questionService.listByIds(idList));
        homeworkDTO.setHomework(homework);
        return new ObjectDataResponse<>(homeworkDTO);
    }

    /**
     * 根据课程测试id 获取该课程测试详情
     *
     * @param examId
     * @return
     */
    @GetMapping("/examDetails")
    @ApiOperation("根据课程测试id 获取该课程测试详情")
    public ObjectDataResponse<ExamDTO> getExamDetailById(@RequestParam() Long examId) {

        Exam exam = examService.getById(examId);

        List<Long> questionIds = GsonUtils.decodeList(exam.getQuestionIds(), Long.class);
        // questionIds = [1,2,3,4]
        List<Question> list = (List<Question>) questionService.listByIds(questionIds);

        ExamDTO examDTO = new ExamDTO();
        examDTO.setExam(exam)
                .setQuestions(list);
        return new ObjectDataResponse<>(examDTO);
    }

}
